package com.woniuxy.flowable.service;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BaoxiuProcessService {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    /**
     * 部署报修流程
     */
    public Deployment deployProcess() {
        log.info("开始部署报修流程...");
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("processes/baoxiu.bpmn20.xml")
                .name("报修流程")
                .deploy();
        log.info("流程部署成功，部署ID: {}", deployment.getId());
        return deployment;
    }

    /**
     * 启动报修流程
     */
    public ProcessInstance startProcess(Long repairOrderId, Long yezhu, Long wuye, Long weixiu, String description) {
        log.info("启动报修流程 - 报修单ID: {}, 业主: {}, 物业: {}, 维修: {}, 描述: {}", 
                repairOrderId, yezhu, wuye, weixiu, description);
        
        Map<String, Object> variables = new HashMap<>();
        variables.put("repairOrderId", repairOrderId);
        variables.put("yezhu", yezhu);
        variables.put("wuye", wuye);
        variables.put("weixiu", weixiu);
        variables.put("description", description);
        
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("baoxiu", repairOrderId.toString(), variables);
        log.info("流程启动成功，流程实例ID: {}", processInstance.getId());
        
        // 自动完成业主提保修单任务
        autoCompleteOwnerTask(processInstance.getId(), yezhu.toString());
        
        return processInstance;
    }
    
    /**
     * 自动完成业主提保修单任务
     */
    private void autoCompleteOwnerTask(String processInstanceId, String ownerId) {
        try {
            // 查找业主的任务
            List<Task> ownerTasks = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .taskAssignee(ownerId)
                    .list();
            
            if (!ownerTasks.isEmpty()) {
                Task ownerTask = ownerTasks.get(0);
                log.info("自动完成业主任务 - 任务ID: {}, 任务名称: {}", ownerTask.getId(), ownerTask.getName());
                
                // 完成任务，推进到下一个节点（物业审批）
                taskService.complete(ownerTask.getId());
                log.info("业主任务自动完成成功");
            } else {
                log.warn("未找到业主任务，流程实例ID: {}", processInstanceId);
            }
        } catch (Exception e) {
            log.error("自动完成业主任务失败", e);
        }
    }

    /**
     * 查询用户任务
     */
    public List<Task> getUserTasks(String assignee) {
        List<Task> tasks = taskService.createTaskQuery()
                .taskAssignee(assignee)
                .list();
        log.info("查询用户 {} 的任务，共找到 {} 个任务", assignee, tasks.size());
        return tasks;
    }

    /**
     * 查询所有待办任务
     */
    public List<Task> getAllTasks() {
        List<Task> tasks = taskService.createTaskQuery().list();
        log.info("查询所有待办任务，共找到 {} 个任务", tasks.size());
        return tasks;
    }

    /**
     * 完成任务
     */
    public void completeTask(String taskId, String outcome) {
        log.info("完成任务 {}，结果: {}", taskId, outcome);
        
        Map<String, Object> variables = new HashMap<>();
        variables.put("outcome", outcome);
        
        taskService.complete(taskId, variables);
        log.info("任务完成成功");
    }

    /**
     * 完成任务（无变量）
     */
    public void completeTask(String taskId) {
        log.info("完成任务 {}", taskId);
        taskService.complete(taskId);
        log.info("任务完成成功");
    }

    /**
     * 获取流程实例信息
     */
    public ProcessInstance getProcessInstance(String processInstanceId) {
        return runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
    }

    /**
     * 获取任务详情
     */
    public Task getTask(String taskId) {
        return taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
    }

    /**
     * 物业审批
     */
    public void approveRepair(Long repairOrderId, Boolean approved, String comment, String userId) {
        log.info("物业审批 - 报修单ID: {}, 审批结果: {}, 审批人: {}", repairOrderId, approved, userId);
        
        // 查找物业审批任务
        List<Task> tasks = taskService.createTaskQuery()
                .processInstanceBusinessKey(repairOrderId.toString())
                .taskAssignee(userId)
                .list();
        
        if (tasks.isEmpty()) {
            throw new RuntimeException("未找到物业审批任务");
        }
        
        Task task = tasks.get(0);
        log.info("找到物业审批任务 - 任务ID: {}, 任务名称: {}", task.getId(), task.getName());
        
        // 设置审批结果
        Map<String, Object> variables = new HashMap<>();
        variables.put("outcome", approved ? "通过" : "不通过");
        if (comment != null && !comment.isEmpty()) {
            variables.put("comment", comment);
        }
        
        // 完成任务
        taskService.complete(task.getId(), variables);
        log.info("物业审批完成 - 审批结果: {}", approved ? "通过" : "驳回");
    }

    /**
     * 维修人员处理报修单
     */
    public void handleRepair(Long repairOrderId, Boolean completed, String feedback, String repairResult, String userId) {
        log.info("维修人员处理 - 报修单ID: {}, 完成状态: {}, 维修人员: {}", repairOrderId, completed, userId);
        
        // 查找维修人员处理任务
        List<Task> tasks = taskService.createTaskQuery()
                .processInstanceBusinessKey(repairOrderId.toString())
                .taskAssignee(userId)
                .list();
        
        if (tasks.isEmpty()) {
            throw new RuntimeException("未找到维修人员处理任务");
        }
        
        Task task = tasks.get(0);
        log.info("找到维修人员处理任务 - 任务ID: {}, 任务名称: {}", task.getId(), task.getName());
        
        // 设置处理结果
        Map<String, Object> variables = new HashMap<>();
        variables.put("outcome", completed ? "通过" : "不通过");
        if (feedback != null && !feedback.isEmpty()) {
            variables.put("feedback", feedback);
        }
        if (repairResult != null && !repairResult.isEmpty()) {
            variables.put("repairResult", repairResult);
        }
        
        // 完成任务
        taskService.complete(task.getId(), variables);
        log.info("维修人员处理完成 - 完成状态: {}", completed ? "完成" : "处理中");
    }

    /**
     * 查询维修人员的待处理任务
     */
    public List<Task> getRepairTasks(String userId) {
        List<Task> tasks = taskService.createTaskQuery()
                .taskAssignee(userId)
                .taskNameLike("%维修人员处理%")
                .list();
        log.info("查询维修人员 {} 的任务，共找到 {} 个任务", userId, tasks.size());
        return tasks;
    }
} 